/*
 * Copyright (C) 2024 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.wakala.employment.fragment.other;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;

import com.android.tu.loadingdialog.LoadingDailog;
import com.hjq.toast.Toaster;
import com.wakala.employment.adapter.entity.LoginInfo;
import com.wakala.employment.adapter.entity.User;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.R;
import com.wakala.employment.activity.MainActivity;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.core.http.subscriber.TipProgressLoadingSubscriber;
import com.wakala.employment.core.http.subscriber.TipRequestSubscriber;
import com.wakala.employment.databinding.FragmentLoginBinding;
import com.wakala.employment.fragment.login.LoginPwdFragment;
import com.wakala.employment.fragment.login.LoginUniFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.DeviceTokenBo;
import com.wakala.employment.http.manager.TokenManager;
import com.wakala.employment.utils.MMKVUtils;
import com.wakala.employment.utils.RandomUtils;
import com.wakala.employment.utils.SettingUtils;
import com.wakala.employment.utils.TokenUtils;
import com.wakala.employment.utils.Utils;
import com.wakala.employment.utils.sdkinit.UMengInit;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.subsciber.ProgressDialogLoader;
import com.xuexiang.xhttp2.subsciber.ProgressLoadingSubscriber;
import com.xuexiang.xhttp2.subsciber.impl.IProgressLoader;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.CountDownButtonHelper;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.ViewUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.progress.loading.LoadingViewLayout;
import com.xuexiang.xui.widget.toast.XToast;
import com.xuexiang.xutil.app.ActivityUtils;
import com.xuexiang.xutil.system.DeviceUtils;
import com.xuexiang.xutil.tip.ToastUtils;


/**
 * 登录页面
 *
 * @author xuexiang
 * @since 2019-11-17 22:15
 */
@Page(anim = CoreAnim.none)
public class LoginFragment extends BaseFragment<FragmentLoginBinding> implements View.OnClickListener {

    private View mJumpView;

    private CheckBox cbProtocol;

    private CountDownButtonHelper mCountDownHelper;

    private IProgressLoader mIProgressLoader;
    private IProgressLoader mIProgressLoaderLogin;
    private IProgressLoader mIProgressLoaderUser;


    @NonNull
    @Override
    protected FragmentLoginBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentLoginBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setImmersive(true);
        titleBar.setBackgroundColor(Color.TRANSPARENT);
        titleBar.setTitle("");
        titleBar.setLeftImageDrawable(ResUtils.getVectorDrawable(getContext(), R.drawable.ic_login_close));
        titleBar.setActionTextColor(ThemeUtils.resolveColor(getContext(), R.attr.colorAccent));
        mJumpView = titleBar.addAction(new TitleBar.TextAction(R.string.title_jump_login) {
            @Override
            public void performAction(View view) {
                ToastUtils.toast("暂不支持不登录浏览");
            }
        });
        return titleBar;
    }

    @Override
    protected void initViews() {
        mIProgressLoader = new ProgressDialogLoader(getContext(), "请求处理中...");
        mIProgressLoaderLogin = new ProgressDialogLoader(getContext(), "登录处理中...");
        mIProgressLoaderUser = new ProgressDialogLoader(getContext(), "正在更新用户数据...");
        mCountDownHelper = new CountDownButtonHelper(binding.btnGetVerifyCode, 60);
        //隐私政策弹窗
        if (!SettingUtils.isAgreePrivacy()) {
            Utils.showPrivacyDialog(getContext(), (dialog, which) -> {
                dialog.dismiss();
                handleSubmitPrivacy();
            });
        }
        cbProtocol = binding.cbProtocol;
        boolean isAgreePrivacy = SettingUtils.isAgreePrivacy() && cbProtocol.isChecked();
        //初始化必须为默认不勾选
        binding.cbProtocol.setChecked(false);
        refreshButton(isAgreePrivacy);
        binding.cbProtocol.setOnCheckedChangeListener((buttonView, isChecked) -> {
            SettingUtils.setIsAgreePrivacy(isChecked);
            refreshButton(isChecked);
        });

        XToast.Config.get().setTextSize(14);

    }

    @Override
    protected void initListeners() {
        binding.btnGetVerifyCode.setOnClickListener(this);
        binding.btnLogin.setOnClickListener(this);
        binding.tvOtherLogin.setOnClickListener(this);
        binding.tvForgetPassword.setOnClickListener(this);
        binding.tvUserProtocol.setOnClickListener(this);
        binding.tvPrivacyProtocol.setOnClickListener(this);
        binding.tvUniLogin.setOnClickListener(this);//使用一键登录按钮
        //处理手机号码输入后处理为123 4567 8900 格式化输出处理
        AppCompatEditText editText = binding.etPhoneNumber;
        binding.etPhoneNumber.addTextChangedListener(new TextWatcher() {
            int beforeTextLength = 0;
            int onTextLength = 0;
            boolean isChanged = false;

            int location = 0;// 记录光标的位置
            private char[] tempChar;
            private StringBuffer buffer = new StringBuffer();
            int konggeNumberB = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                beforeTextLength = s.length();
                if (buffer.length() > 0) {
                    buffer.delete(0, buffer.length());
                }
                konggeNumberB = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == ' ') {
                        konggeNumberB++;
                    }
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                onTextLength = s.length();
                buffer.append(s.toString());
                if (onTextLength == beforeTextLength || onTextLength <= 3
                        || isChanged) {
                    isChanged = false;
                    return;
                }
                isChanged = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isChanged) {
                    location = editText.getSelectionEnd();
                    int index = 0;
                    while (index < buffer.length()) {
                        if (buffer.charAt(index) == ' ') {
                            buffer.deleteCharAt(index);
                        } else {
                            index++;
                        }
                    }

                    index = 0;
                    int konggeNumberC = 0;
                    while (index < buffer.length()) {
                        if ((index == 3 || index == 8)) {
                            buffer.insert(index, ' ');
                            konggeNumberC++;
                        }
                        index++;
                    }

                    if (konggeNumberC > konggeNumberB) {
                        location += (konggeNumberC - konggeNumberB);
                    }

                    tempChar = new char[buffer.length()];
                    buffer.getChars(0, buffer.length(), tempChar, 0);
                    String str = buffer.toString();
                    if (location > str.length()) {
                        location = str.length();
                    } else if (location < 0) {
                        location = 0;
                    }

                    editText.setText(str);
                    Editable etable = editText.getText();
                    Selection.setSelection(etable, location);
                    isChanged = false;
                }
            }
        });
        //处理根据手机号码和验证码输入框焦点事件图标变灰变亮处理
        binding.etPhoneNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    //获得焦点
                    binding.etPhoneNumber.setFloatingLabelTextColor(getResources().getColor(R.color.colorPrimary));
                    binding.imageMobilePhone.setColorFilter(ContextCompat.getColor(getContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
                }else{
                    //失去焦点
                    binding.etPhoneNumber.setFloatingLabelTextColor(getResources().getColor(R.color.gray));
                    binding.imageMobilePhone.setColorFilter(ContextCompat.getColor(getContext(), R.color.gray), PorterDuff.Mode.SRC_IN);
                }
            }
        });
        //
        binding.etVerifyCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    //获得焦点
                    binding.etVerifyCode.setFloatingLabelTextColor(getResources().getColor(R.color.colorPrimary));
                    binding.imageVerifyCode.setColorFilter(ContextCompat.getColor(getContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
                }else{
                    //失去焦点
                    binding.etVerifyCode.setFloatingLabelTextColor(getResources().getColor(R.color.gray));
                    binding.imageVerifyCode.setColorFilter(ContextCompat.getColor(getContext(), R.color.gray), PorterDuff.Mode.SRC_IN);
                }
            }
        });
    }

    private void refreshButton(boolean isChecked) {
        ViewUtils.setEnabled(binding.btnLogin, isChecked);
        ViewUtils.setEnabled(mJumpView, isChecked);
    }

    private void handleSubmitPrivacy() {
        SettingUtils.setIsAgreePrivacy(true);
        UMengInit.init();
        // 应用市场不让默认勾选
        ViewUtils.setChecked(cbProtocol, true);
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_get_verify_code) {
            if (binding.etPhoneNumber.validate()) {
                getVerifyCode(binding.etPhoneNumber.getEditValue());
            }
        } else if (id == R.id.btn_login) {
            if (binding.etPhoneNumber.validate()) {
                if (binding.etVerifyCode.validate()) {
                    loginByVerifyCode(binding.etPhoneNumber.getEditValue(), binding.etVerifyCode.getEditValue());
                }
            }
        } else if (id == R.id.tv_other_login) {
            //XToastUtils.info("其他登录方式");
            openPage(LoginPwdFragment.class);
        } else if (id==R.id.tv_uni_login) {
            openPage(LoginUniFragment.class);
        } else if (id == R.id.tv_forget_password) {
            XToastUtils.info("忘记密码");
        } else if (id == R.id.tv_user_protocol) {
            Utils.gotoProtocol(this, false, true);
        } else if (id == R.id.tv_privacy_protocol) {
            Utils.gotoProtocol(this, true, true);
        }

    }

    /**
     * 获取验证码
     */
    private void getVerifyCode(String phoneNumber) {
        phoneNumber = phoneNumber.replace(" ","");
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setMessage("发送中...")
                .setCancelable(true)
                .setCancelOutside(true);
        LoadingDailog dialog=loadBuilder.create();
        dialog.show();
        // TODO: 2020/8/29 这里只是界面演示而已
        XHttpProxy.proxy(TestApi.IAuthorization.class)
                .sendCode(phoneNumber)
                .subscribeWith(new NoTipRequestSubscriber<Object>() {
                    @Override
                    protected void onSuccess(Object result) {
                        dialog.dismiss();
                        //XToastUtils.success("只是演示，验证码是888888");
                        Toaster.show("验证码已发送");
                        mCountDownHelper.start();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dialog.dismiss();
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });

    }

    /**
     * 根据验证码登录
     *
     * @param phoneNumber 手机号
     * @param verifyCode  验证码
     */
    @SuppressLint("CheckResult")
    private void loginByVerifyCode(String phoneNumber, String verifyCode) {
        phoneNumber = phoneNumber.replace(" ","");
        // TODO: 2020/8/29 这里只是界面演示而已
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setMessage("登录中...")
                .setCancelable(true)
                .setCancelOutside(true);
        LoadingDailog dialog=loadBuilder.create();
        dialog.show();
        //使用XHttpProxy进行接口代理请求
        XHttpProxy.proxy(TestApi.IAuthorization.class)
                .loginMobile(phoneNumber, verifyCode)
                .subscribeWith(new NoTipRequestSubscriber<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo loginInfo) {
                        dialog.dismiss();
                        //ToastUtils.toast("图书购买" + (aBoolean ? "成功" : "失败") + "！");
                        //mRefreshLayout.autoRefresh();
                        onLoginSuccess(loginInfo);
                    }
                    @Override
                    public void onError(ApiException e) {
                        dialog.dismiss();
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });

    }

    /**
     * 登录成功的处理
     */
    private void onLoginSuccess(LoginInfo loginInfo) {
        //String token = RandomUtils.getRandomNumbersAndLetters(16);
        SettingUtils.setIsAgreePrivacy(true);
        UMengInit.init();
        if (TokenUtils.handleLoginSuccess(loginInfo)) {
            //updateDeviceToken();
            getLoginUserInfo();
            //popToBack();
            //ActivityUtils.startActivity(MainActivity.class);
        }
    }

    /**
     * 根据token获取当前登录用户信息
     */
    @SuppressLint("CheckResult")
    private void getLoginUserInfo(){
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setMessage("加载数据中...")
                .setCancelable(true)
                .setCancelOutside(true);
        LoadingDailog dialog=loadBuilder.create();
        dialog.show();
        XHttpProxy.proxy(TestApi.IUserService.class)
                .getLoginUserInfo()
                .subscribeWith(new NoTipRequestSubscriber<User>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(User user) {
                        dialog.dismiss();
                        TokenUtils.setmLoginUser(user);
                        popToBack();
                        ActivityUtils.startActivity(MainActivity.class);
                    }
                    @Override
                    public void onError(ApiException e) {
                        dialog.dismiss();
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });
    }

    @SuppressLint("CheckResult")
    private void updateDeviceToken(){
        DeviceTokenBo deviceTokenBo = new DeviceTokenBo();
        deviceTokenBo.setAndroidId(DeviceUtils.getAndroidID());
        deviceTokenBo.setAndroidVersionName(DeviceUtils.getAndroidVersionName());
        deviceTokenBo.setDeviceModel(DeviceUtils.getDeviceModel());
        deviceTokenBo.setManufacturer(DeviceUtils.getManufacturer());
        deviceTokenBo.setSdkVersionCode(DeviceUtils.getSDKVersionCode()+"");
        deviceTokenBo.setSdkVersionName(DeviceUtils.getSDKVersionName());
        deviceTokenBo.setUmengDeviceToken( MMKVUtils.getString(MMKVUtils.KEY_UMENG_DEVICE_TOKEN,""));
        XHttpProxy.proxy(TestApi.IUserService.class)
                .updateDeviceToken(deviceTokenBo)
                .subscribeWith(new NoTipRequestSubscriber<Object>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(Object object) {

                    }
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });
    }

    @Override
    public void onDestroyView() {
        if (mCountDownHelper != null) {
            mCountDownHelper.recycle();
        }
        super.onDestroyView();
    }



}

